#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>

// #pragma comment(lib, "ws2_32.lib")

#define PORT 8888
#define BUFFER_SIZE 1024

int main() {
    WSADATA wsaData;
    int client_socket;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];

    // 初始化Winsock库
    if (WSAStartup(MAKEWORD(2, 2), &wsaData)!= 0) {
        perror("WSAStartup failed");
        return 1;
    }

    // 创建UDP套接字
    if ((client_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
        perror("Socket creation failed");
        WSACleanup();
        return 1;
    }

    // 初始化服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    while (1) {
        printf("\nEnter a message to send to the server: ");
        fgets(buffer, BUFFER_SIZE, stdin);

        // 发送数据到服务器
        int send_len = sendto(client_socket, buffer, strlen(buffer), 0,
                              (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (send_len == SOCKET_ERROR) {
            perror("Send failed");
            WSACleanup();
            return 1;
        }

        // 接收服务器的响应
        int recv_len = recvfrom(client_socket, buffer, BUFFER_SIZE - 1, 0, NULL, NULL);
        if (recv_len == SOCKET_ERROR) {
            perror("Receive failed");
            WSACleanup();
            return 1;
        }
        buffer[recv_len] = '\0';

        printf("Server response: %s", buffer);
    }


    closesocket(client_socket);
    WSACleanup();
    return 0;
}


